package com.walle.eve.aspect;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.walle.eve.datasource.DynamicRoutingContextHolder;
import com.walle.eve.datasource.RoutingDataSource;
import com.walle.eve.datasource.RoutingStrategy;

/**
 * 
 * 用于动态切换数据源
 * 
 * @author xudawei
 * @date 2017年11月10日 下午2:08:56
 */
@Aspect
@Component
public class RoutingDataSourceAspect {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Before("execution( * com.walle.eve.mapper..*.*(..))")
	public void routingDataSource(JoinPoint point) {
		Object target = point.getTarget();
		String methodName = point.getSignature().getName();
		Class<?>[] clazz = target.getClass().getInterfaces();

		logger.debug("before class:{} method:{} execute", clazz[0].getName(), methodName);

		Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		try {
			Method method = clazz[0].getMethod(methodName, parameterTypes);
			if (method != null && method.isAnnotationPresent(RoutingDataSource.class)) {
				RoutingDataSource data = method.getAnnotation(RoutingDataSource.class);
				DynamicRoutingContextHolder.setRouteStrategy(data.value());
				logger.debug("class:{} method:{} use data source :{}", clazz[0].getName(), methodName, data.value());
			} else {
				// 如果没有指定数据源，默认使用该数据源
				DynamicRoutingContextHolder.setRouteStrategy(RoutingStrategy.DB1);
				logger.debug("class:{} method:{} use default data source :{}", clazz[0].getName(), methodName, RoutingStrategy.DB1);
			}
			
		} catch (Exception e) {
			logger.error("routing data source error", e);
		}
	}
}
